﻿using System;
using System.Web.Caching;

namespace DotNet.Helper
{
    /// <summary>
    /// Web运行时缓存
    /// </summary>
    public class HttpRuntimeCacheHelper
    {
        /// <summary>
        /// 缓存获取
        /// </summary>
        /// <param name="cacheKey">缓存主键</param>
        /// <returns></returns>
        public static object GetHttpRuntimeCache(string cacheKey)
        {
            return System.Web.HttpRuntime.Cache.Get(cacheKey);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheKey">缓存主键</param>
        /// <param name="value">缓存值</param>
        public static void SetHttpRuntimeCache(string cacheKey, object value)
        {
            System.Web.HttpRuntime.Cache.Insert(cacheKey, value);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheKey">缓存主键</param>
        /// <param name="value">缓存值</param>
        /// <param name="minutes">过期时间(分钟)</param>
        public static void SetHttpRuntimeCache(string cacheKey, object value, int minutes)
        {
            System.Web.HttpRuntime.Cache.Insert(cacheKey, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(minutes));
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheKey">缓存主键</param>
        /// <param name="value">缓存值</param>
        /// <param name="cacheDependency">所插入对象的文件依赖项或缓存键依赖项。当任何依赖项更改时，该对象即无效，并从缓存中移除。如果没有依赖项，则此参数包含 null。</param>
        public static void SetHttpRuntimeCache(string cacheKey, object value, CacheDependency cacheDependency)
        {
            System.Web.HttpRuntime.Cache.Insert(cacheKey, value, cacheDependency);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheKey">缓存主键</param>
        /// <param name="value">缓存值</param>
        /// <param name="minutes">过期时间(分钟)</param>
        /// <param name="onRemoveCallback">在从缓存中移除对象时将调用的委托（如果提供）。当从缓存中删除应用程序的对象时，可使用它来通知应用程序。</param>
        public static void SetHttpRuntimeCache(string cacheKey, object value, int minutes, CacheItemRemovedCallback onRemoveCallback)
        {
            System.Web.HttpRuntime.Cache.Insert(cacheKey, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(minutes), CacheItemPriority.Normal, onRemoveCallback);
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="cacheKey">缓存主键</param>
        public static void RemoveRuntimeCache(string cacheKey)
        {
            if (System.Web.HttpRuntime.Cache[cacheKey] != null)
                System.Web.HttpRuntime.Cache.Remove(cacheKey);
        }

    }
}
